<?php
namespace app\admin\controller;
use app\model\Category as CategoryModel;
use app\model\Article as ArticleModel;
use think\Db;


class Article extends Base
{
    public function __construct(){
        $model = new ArticleModel();
        $this->model = $model;
        parent::__construct();
        
        $page_info = $this->page_info;
        $page_info['title'] = '文章';

        if ( in_array($page_info['action'], ['add','edit']) ) {
            // $this->page_info['view'] = 'save';

            // $tags = Db::name('tags')->select();
            // $pids = $this->getCategoryRecursion(0,0,$pid_map);
            $fields = [
                // 'category_id'=>['name'=>'分类','type'=>'select1','params'=>$pids],
                'title'=>['name'=>'标题','type'=>'text'],
                'subtitle'=>['name'=>'副标题','type'=>'text'],
                'sort'=>['name'=>'排序值','type'=>'text'],
                'image'=>['name'=>'图片','type'=>'file'],
                // 'description'=>['name'=>'描述','type'=>'textarea'],
                'content'=>['name'=>'内容','type'=>'ueditor']
            ];
            $valids = createPageValid($fields);
            $this->assign([
                'fields'=>$fields,
                'valids'=>$valids
            ]);
        }

        $this->assign([
            'model'=>$this->model,
            'page_info'=>$page_info
        ]);
    }

    // public function index(){
    //     $model = $this->model;
    //     $map_params = [
    //         ['key'=>'title','type'=>'like']
    //     ];
    //     $map = getSearchParam($map_params);
      
    //     $search_params = [
    //         [
    //             ['key'=>'title','name'=>'标题','type'=>'text'],
    //         ]
    //     ];
    //     $this->assign([
    //         'search_params'=>$search_params
    //     ]);

    //     return parent::index($map);
    // }

    public function index(){
        $model = $this->model;
        $map_params = [
            ['key'=>'title','type'=>'like']
        ];
        $map = getSearchParam($map_params);
      
        $search_params = [
            [
                ['key'=>'title','name'=>'标题','type'=>'text'],
            ]
        ];
        $this->assign([
            'search_params'=>$search_params
        ]);
        $page_param = [
            'page'=>input('page',1),
            'list_rows'=>input('page_size',10)
        ];
        $list = $model->where($map)->order('ctime','desc')->paginate($page_param);
        $page = $list->render();
        $list = $list->toarray();
        foreach ($list['data'] as $k => $vo) {
            
        }
        
        return view('index', [
            'list'=>$list,
            'page'=>$page
        ]);
    }

    public function add(){
        if (request()->isPost()) {
            $fields = [
                'must'=>['title','subtitle'],
                'nomust'=>['sort','image','description','content']
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                $this->error($save_data['error_msg']);
            }
        }
        return parent::saveData($save_data);
    }

    public function edit(){
        $id = input('id');
        if (empty($id)) { $this->error('id不能为空'); }
        
        if (request()->isPost()) {
            $fields = [
                'must'=>['title','subtitle'],
                'nomust'=>['sort','image','description','content']
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                $this->error($save_data['error_msg']);
            }
        }
        return parent::updateData($id,$save_data);
    }

    // 递归获取
    public static function getCategoryRecursion($id=0,$num=0,$map=[]){
        $model = new CategoryModel();
        $tmp_map = $map;
        $tmp_map[] = ['pid','=',$id];
        $pids = $model->where($tmp_map)->order('sort desc,id asc')->select()->toarray();
        $new_pids = [];
        $childs_num = $num + 1;
        foreach ($pids as $vo) {
            if ($num == 0) {
                $new_pids[$vo['id']] = $vo['name'];
            }else{
                $new_pids[$vo['id']] = stringRange('&nbsp;',$num * 3).'☇'.$vo['name'];
            }
            $childs = \app\admin\controller\Category::getCategoryRecursion($vo['id'],$childs_num,$map);
            if (!empty($childs)) {
                foreach ($childs as $child_k => $child_v) {
                    $new_pids[$child_k] = $child_v;
                }
            }
        }
        return $new_pids;
    }

    public function pachong(){
        $api_url = 'https://www.ctyun.cc/News-3.html';
        $response = httpRequest($api_url);
        $response = substr($response,strpos( $response,'<ul class="cloList">'),strpos($response, '<nav class="pageNav anim fadeInUp">')-strpos( $response,'<ul class="cloList">'));

        $response = str_replace(['</li>'],"骉",$response);
        preg_match_all("/<li[^<>]*>([^骉]*)骉/siu", $response,$contents);
        $tmps = $contents[1];
        $list = [];
        foreach ($tmps as $k => $response) {
            // dump($response);die;
            // if ($k != 2) {
            //     continue;
            // }
            $data = [];
            preg_match("/<a href=\"([^\"]*)\"/si", $response,$contents);
            $data['subtitle'] = $contents[1];

            preg_match("/<img src=\"([^\"]*)\"/si", $response,$contents);
            $data['image'] = $contents[1];

            preg_match("/<h4><a[^<>]*>(.*)<\/a>/si", $response,$contents);
            $data['title'] = $contents[1];
            
            preg_match("/<div class=\"h2\">([^<>]*)<\/div>/si", $response,$contents);
            $data['description'] = $contents[1];

            $data['ctime'] = time();
            $list[] = $data;
        }
        // dump($list);die;
        Db::name('article')->insertAll($list);
    }

    public function pachong2(){
        $list = Db::name('article')->select();
        foreach ($list as $k => $vo) {
            $data = [];
            $response = httpRequest($vo['subtitle']);
            // dump($vo['subtitle']);
            // dump($response);die;

            preg_match("/<div class=\"article-main\">(.*)<\/div>/i", $response,$contents);
            $data['content'] = $contents[1];

            Db::name('article')->where('id',$vo['id'])->update($data);
        }
        dump($list);die;
    }

    public function pachong3(){
        $list = Db::name('product')->where(Db::raw('url is not null'))->select();
        foreach ($list as $k => $vo) {
            $data = [];
            $response = httpRequest($vo['url']);
            // dump($vo['url']);
            // dump($response);die;

            preg_match("/<h1 class=\"shopTit\">(.*)<\/h1>/si", $response,$contents);
            $contents = $contents[1];
            preg_match("/<span>(.*)<\/span>/si", $contents,$fields);
            $data['subtitle'] = $fields[1];

            preg_match("/<div class=\"umDes\">(.*)<\/div>/i", $response,$contents);
            $data['mid_description'] = $contents[1];
            
            preg_match("/<a class=\"qq\" href=\"([^\"]*)\"/si", $response,$contents);
            $data['gw_url'] = $contents[1];

            preg_match("/<span class=\"vip1\">(.*)<\/span>/i", $response,$contents);
            $contents = $contents[1];
            preg_match("/<em>(.*)<\/em>/si", $contents,$fields);
            $data['discount'] = $fields[1];
            
            preg_match("/<div class=\"article-main\">(.*)<\/div>/i", $response,$contents);
            $contents = $contents[1];
            $contents = explode('</blockquote>', $contents);
            foreach ($contents as $content) {
                if (strpos($content, '<blockquote>') !== false) {
                    $data['max_description'][] = str_replace(['<blockquote>','<p>','</p>','<div>','</div>','<span>','</span>'],'',$content);
                }else{
                    $data['content'] = $content;
                }
            }
            if (!empty($data['max_description'])) {
                $data['max_description'] = implode("\r\n",$data['max_description']);
            }

            preg_match("/<img class=\"owl-lazy\" data-src=\"([^\"]*)\"/si", $response,$contents);
            $data['image'] = $contents[1];
            if (!empty($data['image'])) {
                $data['image'] = 'https://www.ctyun.cc'.$data['image'];
            }
            
            Db::name('product')->where('id',$vo['id'])->update($data);





         
        }
        dump($list);die;
    }

}
